package com.rran.study.algorithm.easy.day10;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yy
 * @Type Solution.java
 * @Desc
 * @date 2020/11/24
 * { ‘A’: 1, ‘B.A’: 2, ‘B.B’: 3, ‘CC.D.E’: 4, ‘CC.D.F’: 5}.
 */


public class Solution2 {

    public static void main(String[] args) {
        //初始化map
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("A", 1);
        map.put("B.A", 2);
        map.put("B.B", 3);
        map.put("CC.D.E", 4);
        map.put("CC.D.F", 5);

        Map<String, Object> result = new HashMap<String, Object>();
        for (String key : map.keySet()) {
            buildMap(result, key, map.get(key));
        }
        System.out.println(map);
    }

    private static void buildMap(Map<String, Object> map, String key, Integer value) {
        if (key.contains(".")) {
            int index = key.indexOf(".");
            String first = key.substring(0, index);
            String end = key.substring(index + 1);
            HashMap<String, Object> newMap = new HashMap<String, Object>();
            if (!map.containsKey(first)) {
                map.put(first, newMap);
            } else {
                newMap = (HashMap<String, Object>) map.get(first);
            }
            buildMap(newMap, end, value);
        } else {
            map.put(key, value);
        }

    }


}
